package com.xiaoxx.controller.chat;

import com.alibaba.dashscope.exception.InputRequiredException;
import com.alibaba.dashscope.exception.NoApiKeyException;
import com.xiaoxx.common.result.R;
import com.xiaoxx.model.dto.chat.ChatDto;
import com.xiaoxx.model.vo.chat.ChatContentListVo;
import com.xiaoxx.model.vo.chat.ChatTokenStatisticsAllVo;
import com.xiaoxx.model.vo.chat.ChatTokenStatisticsVo;
import com.xiaoxx.service.ChatContentService;
import io.swagger.annotations.*;
import lombok.extern.slf4j.Slf4j;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.mvc.method.annotation.SseEmitter;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;
import java.io.IOException;
import java.util.List;

/**
 * @author :HX
 * @date : 2023/7/20
 */
@Slf4j
@Validated
@RestController
@RequestMapping("/api/chat")
@Api(value = "ChatController", tags = "聊天管理")
public class ChatController {
    @Resource
    private ChatContentService chatContentService;

    @ApiOperation("聊天")
    @ApiImplicitParams({@ApiImplicitParam(name = "chatVo", value = "开始聊天", required = true, dataType = "ChatVo", paramType = "Body")})
    @RequestMapping(value = "/start", method = RequestMethod.POST)
    public void start(@Valid @RequestBody ChatDto chatVo) throws NoApiKeyException, InputRequiredException, IOException {
        chatContentService.start(chatVo);
    }

    @ApiOperation("创建sse链接")
    @RequestMapping(value = "/addSse", method = RequestMethod.GET)
    public SseEmitter addSse(HttpServletResponse response, @RequestParam String id) {
        response.addHeader("Content-Type", "text/event-stream");
        return chatContentService.addSse(id);
    }

    @GetMapping("/list")
    @ApiOperation("聊天记录列表")
    @ApiResponses(value = {@ApiResponse(response = ChatContentListVo.class, code = 200, message = "响应成功")})
    public R<List<ChatContentListVo>> list(@RequestParam String chatMenuId) {
        return R.success(chatContentService.getList(chatMenuId));
    }

    @GetMapping("/tokens/statistics")
    @ApiOperation("统计")
    @ApiResponses(value = {@ApiResponse(response = ChatContentListVo.class, code = 200, message = "响应成功")})
    public R<List<ChatTokenStatisticsVo>> tokenStatistics(@RequestParam int type) {
        return R.success(chatContentService.tokenStatistics(type));
    }

    @GetMapping("/tokens/statistics/all")
    @ApiOperation("统计")
    public R<ChatTokenStatisticsAllVo> tokenStatisticsAll() {
        return R.success(chatContentService.tokenStatisticsAll());
    }
}
